package com.etc;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DbUtil {
    private static Connection connection=null;
    private static PreparedStatement preparedStatement=null;
    private static ResultSet resultSet=null;
    private static Properties properties=new Properties();

    static {
        try {
            properties.load(DbUtil.class.getClassLoader().getResourceAsStream("com/etc/db.properties"));
            Class.forName(properties.getProperty("driver"));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close();
        }
    }
    public static Connection getConnection(){
        try {
            connection= DriverManager.getConnection(properties.getProperty("url"),properties);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     *
     * @param sql
     * @param params
     * @return
     */


    public static  int executeUpdate(String sql,Object...params){
        connection=getConnection();
        int result=0;
        try {
            preparedStatement=connection.prepareStatement(sql);
            //将？替换成param
            for (int i = 0; i<params.length; i++){
                preparedStatement.setObject(i+1,params[i]);
            }
            result = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close();
        }
        return result;
    }
    /**
     * 关闭资源
     */
    public static void close(){
        try{
            if (null!=resultSet){
                resultSet.close();
            }
            if (null!=preparedStatement){
                preparedStatement.close();
            }
            if (null!=connection){
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param sql
     * @param params
     */
    public static ResultSet executeQuery(String sql, Object...params) {
        connection = getConnection();
        try {
            preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
           resultSet= preparedStatement.executeQuery(sql);
            for (int i = 0; i<params.length; i++){
                preparedStatement.setObject(i+1,params[i]);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }

}
